package ext.tianma.part.statute;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import ext.com.iba.IBAUtil;
import ext.tianma.part.PartCommands;
import ext.tianma.util.IbaAttributeUtil;
import ext.tianma.util.TianMaConstants;
import ext.tianma.workflow.BomWorkFlowUtil;
import wt.doc.WTDocument;
import wt.doc.WTDocumentHelper;
import wt.fc.ObjectReference;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.log4j.LogR;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.project.Role;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.team.Team;
import wt.team.TeamManaged;
import wt.type.ClientTypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.workflow.engine.WfProcess;

public class StatuteProcess {
	private static final Logger log = LogR.getLogger(StatuteProcess.class.getName());
	public static String STATUTE_PATH = "/ptc/Windchill/codebase/ext/tianma/part/config/status.xlsx";
	// 角色为法规审核
	private static String internal_value = "lawAssessor";
	// 固定参与者为李在纯
	private static String name = "A050408";

	/***
	 * 读取excel获取中英文名称
	 * 
	 * @return
	 * @throws WTException
	 */
	public static List<String> getCascade() throws WTException {

		log.info("===>>start==>>action===>>");
		InputStream is = null;
		Workbook wb = null;
		Workbook workbook = null;
		try {
			log.info("CASCADE_PATH===>>" + STATUTE_PATH);
			is = new FileInputStream(STATUTE_PATH);

			log.info("=====>>>" + STATUTE_PATH);
			if (!is.markSupported()) {
				is = new PushbackInputStream(is, 8);
			}

			if (POIFSFileSystem.hasPOIFSHeader(is)) {
				// 2003及以下
				wb = new HSSFWorkbook(is);
			} else if (POIXMLDocument.hasOOXMLHeader(is)) {
				// 2007及以上
				wb = new XSSFWorkbook(is);
			} else {
				// 不是Excel
				throw new WTException("Incorrect configuration file path.");
			}

			workbook = wb;

			List<String> excelList = new ArrayList<String>();
			Sheet sheet = workbook.getSheetAt(0);
			Row row;
			Cell cell;
			String tempVal;

			// 第一行为表头，从第二行开始遍历
			for (int i = 1, rowNum = sheet.getLastRowNum(); i <= rowNum; i++) {
				if ((row = sheet.getRow(i)) != null) {
					// 遍历列
					int cellNum = row.getLastCellNum();
					String str = "";
					for (int j = 0; j <= cellNum; j++) {
						cell = row.getCell(j);
						if (cell == null || (tempVal = cell.getStringCellValue()) == null) {
							str = "";
							continue;
						} else {
							str = tempVal.trim();
						}
						log.info("cellArray=====>>>>>>>>>>>>>>>>" + str);
						excelList.add(str);
					}
				}
			}
			return excelList;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new WTException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new WTException(e);
		} finally {
			close(is);
		}
	}

	/***
	 * 验证是否需要通过法规审核
	 * 
	 * @param object
	 * @return
	 * @throws RemoteException
	 * @throws WTException
	 */
	public static boolean getPartCNAndENName(WTObject object) throws RemoteException, WTException {
		boolean flag = false;
		String partCNAndENName = "";
		String partEnvProtectionCategory = "";
		List<String> list = getCascade();
		WTPart part = null;
		if (object instanceof WTPart) {
			part = (WTPart) object;
			partCNAndENName = ((String) IBAUtil.getIBAValue(part, "partCNAndENName"));
			if (checkEffectiveSite(part)) {
				if (partCNAndENName != null) {
					partEnvProtectionCategory = ((String) IBAUtil.getIBAValue(part, "partEnvProtectionCategory"));
					for (String partCNAndENName2 : list) {
						log.info("=====partCNAndENName2====" + partCNAndENName2);
						log.info("=====partCNAndENName2====" + partEnvProtectionCategory);
						if (partCNAndENName.equals(partCNAndENName2) && !("NA").equals(partEnvProtectionCategory)) {
							return true;
						}
					}
				}
			}
		}
		return flag;
	}

	/**
	 * 判定料号生效地是否包含深圳
	 * 
	 * @param part
	 * @return boolean
	 */
	private static boolean checkEffectiveSite(WTPart part) {
		List<String> effectiveSite = IbaAttributeUtil.getAttributeValues(part, "partNumberEffectiveSite");
		boolean temp = false;
		log.info("effectiveSite===>>" + effectiveSite);
		for (String site : effectiveSite) {
			if (site.contains(TianMaConstants.EffectiveSite.C01.getSite())
					|| site.contains(TianMaConstants.EffectiveSite.C02.getSite())
					|| site.contains(TianMaConstants.EffectiveSite.C04.getSite())
					|| site.contains(TianMaConstants.EffectiveSite.C08.getSite())) {
				temp = true;
				break;
			}
		}
		return temp;
	}

	/**
	 * 给角色添加用户
	 * 
	 * @param self           obj
	 * @param internal_value 角色名
	 * @param name           用户名
	 * @throws WTPropertyVetoException
	 * @throws WTException
	 * @throws RemoteException
	 */
	public static void addPrincipalToRole(WTObject primaryBusinessObject, ObjectReference self)
			throws WTPropertyVetoException, WTException, RemoteException {
		if (primaryBusinessObject instanceof WTPart) {
			WTPart part = (WTPart) primaryBusinessObject;
			String viewName = part.getViewName();
			log.info("viewName111====>>>" + viewName);
			// boolean ben = getPartCNAndENName(primaryBusinessObject);
			// log.info("viewName====>>>" + ben);
			// if (ben) {

			WfProcess process = BomWorkFlowUtil.getProcess(self);
			wt.team.Team team = null;
			try {
				team = getTeam(process);
			} catch (Exception ex) {
				ex.printStackTrace();
				throw new WTException(ex);
			}

			Role theRole = Role.toRole(internal_value);
			// 判断当前角色是否有人
			// Role role = Role.toRole((String) roleV.elementAt(i));
			// Enumeration enums = team.getPrincipalTarget(role);
			//
			// boolean bCheckRoleOK = false;
			//
			// while (enums != null && enums.hasMoreElements())
			// {
			// WTPrincipalReference principalRef = (WTPrincipalReference)
			// enums.nextElement();
			// if (principalRef == null || principalRef.isDisabled())
			// continue;
			// bCheckRoleOK = true;
			// break;
			// }
			WTUser user = getUserByName(name);
			log.info("theRole===" + theRole + "==>>user===>>" + user);
			if (user == null) {
				throw new WTException("没有找到用户: [" + user + "] ");
			} else {
				team.addPrincipal(theRole, user);
			}
			PersistenceHelper.manager.refresh(team);

			// }

		}
	}

	// 根据用户名查询WTUser对象
	public static WTUser getUserByName(String username) throws WTException {
		WTUser user = null;
		QuerySpec qs = new QuerySpec(WTUser.class);
		SearchCondition sc = new SearchCondition(WTUser.class, WTUser.NAME, "=", username);
		qs.appendWhere(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			user = (WTUser) qr.nextElement();
		}
		return user;
	}

	/**
	 * 根据WfProcess对象，获得团队
	 * 
	 * @param process
	 * @return
	 * @throws Exception
	 */
	public static Team getTeam(WfProcess process) throws Exception {

		Team team = null;
		ReferenceFactory rf = new ReferenceFactory();
		String oid = rf.getReferenceString(process);
		WTObject wtobject = (WTObject) rf.getReference(oid).getObject();
		if (wtobject instanceof TeamManaged) {
			team = (Team) ((TeamManaged) wtobject).getTeamId().getObject();
		} else if (wtobject instanceof Team) {
			team = (Team) wtobject;
		}
		return team;
	}

	/**
	 * 判断物料是否关联了说明方文档
	 * 
	 * @throws WTException *
	 * 
	 */
	public static boolean getPartDoLinkDoucment(WTObject primaryBusinessObject) throws WTException {
		boolean bool = true;
		if (primaryBusinessObject instanceof WTPart) {
			WTPart part = (WTPart) primaryBusinessObject;
			QueryResult qr = WTPartHelper.service.getDescribedByDocuments(part);
			if (qr.hasMoreElements()) {
				bool = false;
			} else {
				bool = true;
				// throw new WTException("注意上传环保资料，否则会被法规审核节点驳回，如有特殊沟通请附上沟通证据!");
			}
		}

		return bool;
	}

	/**
	 * 判断物料是否关联了说明方文档
	 * 
	 * @throws WTException *
	 * 
	 */
	public static void checkPartLink(WTObject primaryBusinessObject) throws WTException {
		try {
			if (primaryBusinessObject instanceof WTPart) {
				WTPart part = (WTPart) primaryBusinessObject;
				QueryResult qr = WTPartHelper.service.getDescribedByDocuments(part);
				WTPart part2 = PartCommands.getWTPartByNumber(part.getNumber());
				QueryResult qr2 = WTPartHelper.service.getDescribedByDocuments(part2);
				log.info("qr====>>" + qr.size());
				log.info("qr2====>>" + qr2.size());
				if (qr.size() == 0) {
					throw new WTException("注意上传环保资料，否则会被法规审核节点驳回，如有特殊沟通请附上沟通证据,如果忽略，请去除勾选后完成!");
				}
				boolean flag = true;
				while (qr.hasMoreElements()) {
					WTDocument doc = (WTDocument) qr.nextElement();
					String docType = ClientTypedUtility.getLocalizedTypeName(doc, Locale.CHINA);
					if ("环保资料".equals(docType)) {
						flag = false;
					}
				}
				if (flag) {
					throw new WTException("注意上传环保资料，否则会被法规审核节点驳回，如有特殊沟通请附上沟通证据,如果忽略，请去除勾选后完成!");
				}
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭资源
	 * 
	 * @param closeable
	 */
	public static void close(Closeable closeable) {
		try {
			if (closeable != null) {
				closeable.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void ReadExcel() {

	}

}
